package com.example.springbootasyncdemo.service;
import com.example.springbootasyncdemo.entity.FutureResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;

import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class TestService {
    @Autowired
    private ApplicationContext applicationContext;

    public ArrayList<String> testAsyncFeedBack() throws Exception {
        CountDownLatch countDownLatch = new CountDownLatch(3);
        //这里展示了一种方法，可用于在一个类中调用标注有@async 或者 @transactional等基于aop的注解的方法，并使注解生效
        //这个 TestService.class 就是当前类
        //applicationContext 直接@autowire注入进来就行
        TestService proxyService = applicationContext.getBean(TestService.class);
        List<String> nameList = new ArrayList<>();
        Future<FutureResult<List<String>>> future1 = proxyService.getNameList(nameList, countDownLatch);

        List<String> addressList = new ArrayList<>();
        Future<FutureResult<List<String>>> future2 = proxyService.getAddressList(addressList, countDownLatch);

        List<String> numberList = new ArrayList<>();
        Future<FutureResult<List<String>>> future3 = proxyService.getNumberList(numberList, countDownLatch);

        //等待子线程执行完毕
        countDownLatch.await();
        //三个子线程全部正常执行，才给接口调用方返回数据，否则抛出异常（各位可根据看情况是否需要这么做）
        if (future3.get().getStatus() == 1 && future3.get().getStatus() == 1 && future3.get().getStatus() == 1) {
            ArrayList<String> respList = new ArrayList<>();
            respList.addAll(future1.get().getData());
            respList.addAll(future2.get().getData());
            respList.addAll(future3.get().getData());
            log.info("main 线程执行完毕");
            return respList;
        } else {
            log.info("main 线程执行完毕");
            throw new Exception("多线程处理发生异常");//这里只是简单的new了一个异常，各位看官根据自己业务处理
        }
    }

    @Async("asyncServiceExecutor")
    public Future<FutureResult<List<String>>> getNumberList(List<String> numberList, CountDownLatch countDownLatch) {
        log.info("getNumberList...");
        long begin = System.currentTimeMillis();
        log.info("线程[{}]执行开始",Thread.currentThread().getName());
        FutureResult<List<String>> listFutureResult = new FutureResult<>();//自己定义了一个future的返回的结果
        ArrayList<String> strings = new ArrayList<>();
        listFutureResult.setData(strings);
        try {
            strings.add("number");
            TimeUnit.SECONDS.sleep(10);//模拟耗时业务代码
            // 模拟异常情况
//            int a = 1 / 0;
            listFutureResult.setStatus(1); //如果正常执行完业务代码，这里就设置状态为1
            log.info("getNumberList 执行完了");
        } catch (Exception e) {
            log.error("getNumberList error...", e);
            listFutureResult.setStatus(0); //如果执行业务代码发生异常，这里就设置状态为0
            listFutureResult.setException(e);//如果需要异常信息，也可在此处把异常塞回去
        } finally {
            //最终不管该子线程是否抛出异常一定要调用countDown方法，要不然主线程会一直等待这个子线程调用countDown
            countDownLatch.countDown();
        }
        long end = System.currentTimeMillis();

        log.info("线程[{}]执行结束,耗时{}ms",Thread.currentThread().getName(), end-begin);
        return new AsyncResult<>(listFutureResult);
    }

    @Async("asyncServiceExecutor")
    public Future<FutureResult<List<String>>> getAddressList(List<String> addressList, CountDownLatch countDownLatch) {
        log.info("getAddressList...");
        long begin = System.currentTimeMillis();
        log.info("线程[{}]执行开始",Thread.currentThread().getName());
        FutureResult<List<String>> listFutureResult = new FutureResult<>();
        ArrayList<String> strings = new ArrayList<>();
        listFutureResult.setData(strings);
        try {
            strings.add("address");
            TimeUnit.SECONDS.sleep(7); //模拟耗时业务代码
            listFutureResult.setStatus(1);
            countDownLatch.countDown();
            log.info("getAddressList 执行完了");
        } catch (Exception e) {
            log.error("getAddressList error...", e);
            listFutureResult.setStatus(0);
            listFutureResult.setException(e);
        } finally {
            countDownLatch.countDown();
        }
        long end = System.currentTimeMillis();
        log.info("线程[{}]执行结束,耗时{}ms",Thread.currentThread().getName(), end-begin);
        return new AsyncResult<>(listFutureResult);
    }

    @Async("asyncServiceExecutor")
    public Future<FutureResult<List<String>>> getNameList(List<String> nameList, CountDownLatch countDownLatch) {
        log.info("getNameList start...");
        long begin = System.currentTimeMillis();
        log.info("线程[{}]执行开始",Thread.currentThread().getName());
        FutureResult<List<String>> listFutureResult = new FutureResult<>();
        ArrayList<String> strings = new ArrayList<>();
        listFutureResult.setData(strings);
        try {
            strings.add("name");
            TimeUnit.SECONDS.sleep(15);//模拟耗时业务代码
            listFutureResult.setStatus(1);
            countDownLatch.countDown();
            ;
            log.info("getNameList 执行完了");
        } catch (Exception e) {
            log.error("getNameList error...", e);
            listFutureResult.setStatus(0);
            listFutureResult.setException(e);
        } finally {
            countDownLatch.countDown();
        }
        long end = System.currentTimeMillis();
        log.info("线程[{}]执行结束,耗时{}ms",Thread.currentThread().getName(), end-begin);
        return new AsyncResult<>(listFutureResult);
    }



}
